﻿using System;
using System.IO;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Admin.Common;
using Admin.IService;
using Admin.Model;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace Admin.Web.Controllers.Api
{
    public class SysUserController : ApiController
    {
        private ISysUserService _sysUserService;
        private ISysUserRoleService _sysUserRoleService;
        public SysUserController(ISysUserService sysUserService, ISysUserRoleService sysUserRoleService)
        {
            _sysUserService = sysUserService;
            _sysUserRoleService = sysUserRoleService;
        }

        #region 查询接口
        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="page">当前页</param>
        /// <param name="pageSize">每页大小</param>
        /// <param name="account">账户</param>
        /// <param name="phone">手机号</param>
        /// <param name="status">状态</param>
        /// <param name="startTime">创建时间</param>
        /// <param name="endTime">创建时间</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<InfoModel> QueryUserPage(int page = 0, int pageSize = 10, string account = null, string phone = null, int? status = null, string startTime = null, string endTime = null)
        {
            #region 查询条件
            string sqlWhere = "";
            if (account != null)
            {
                sqlWhere = $" {sqlWhere} and Account like concat('%', @account, '%')";
            }
            if (phone != null)
            {
                sqlWhere = $" {sqlWhere} and Phone  like concat('%', @phone, '%') ";
            }
            if (status != null)
            {
                sqlWhere = $" {sqlWhere} and Status=@status ";
            }
            if (startTime != null)
            {
                sqlWhere = $" {sqlWhere} and date_format(CreateTime,'%y%m%d') >= date_format(@startTime,'%y%m%d')";
            }
            if (endTime != null)
            {
                sqlWhere = $" {sqlWhere} and date_format(CreateTime,'%y%m%d') <= date_format(@endTime,'%y%m%d')";
            }
            #endregion

            var rows = await _sysUserService.GetPage(page, pageSize, new { account, phone, status, startTime, endTime }, sqlWhere);
            int total = await _sysUserService.GetCount(new { account, phone, status, startTime, endTime }, sqlWhere);
            return DataReturn(new { total, rows }, "查询");
        }

        /// <summary>
        /// 授权用户查询
        /// </summary>
        /// <param name="page"></param>
        /// <param name="pageSize"></param>
        /// <param name="roleId"></param>
        /// <param name="account"></param>
        /// <param name="phone"></param>
        /// <returns></returns>
        [HttpGet]
        public InfoModel QueryUserByRoleId(int page, int pageSize, string roleId, string account = null, string phone = null, bool non = false)
        {
            #region sqlWhere
            string sqlWhere = $" ur.RoleId{(non ? "!=" : "=")}@roleId";
            if (account != null)
            {
                sqlWhere = $"{sqlWhere} and u.Account like concat('%', @account, '%')";
            }
            if (phone != null)
            {
                sqlWhere = $"{sqlWhere} and u.Phone like concat('%', @phone, '%')";
            }
            #endregion
            int total;
            var rows = _sysUserService.QueryUserByUserId(page, pageSize, new { roleId, account, phone }, sqlWhere, out total);
            return DataReturn(new { total, rows }, "查询");
        }



        #region 验证
        [HttpGet]
        public async Task<bool> CheckAccount(string Account, string Id = "") => await _sysUserService.IsExist(new { Account, Id }, $"Account=@Account{(Id != "" ? " and Id!=@Id" : "")}");
        [HttpGet]
        public async Task<bool> CheckPhone(string Phone, string Id = "") => await _sysUserService.IsExist(new { Phone, Id }, $"Phone=@Phone{(Id != "" ? " and Id != @Id" : "")}");
        [HttpGet]
        public async Task<bool> CheckEmail(string Email, string Id = "") => await _sysUserService.IsExist(new { Email, Id }, $"Email=@Email{(Id != "" ? " and Id != @Id" : "")}");
        #endregion

        #endregion

        #region 操作接口

        /// <summary>
        /// 新增用户
        /// </summary>
        /// <param name="sysUser"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<InfoModel> AddSave([FromBody]RequestUser sysUser)
        {
            #region 数据封装
            sysUser.Salt = EncryptionHelper.Salt();
            sysUser.Pwd = EncryptionHelper.Md5(sysUser.Account + sysUser.Pwd, sysUser.Salt);
            sysUser.CreateTime = DateTime.Now;
            sysUser.CreateBy = HttpContext.User.Claims.Where(o => o.Type == ClaimTypes.NameIdentifier).FirstOrDefault().Value;
            #endregion

            int res = await _sysUserService.Insert(sysUser, new string[] { "Name", "Phone", "Sex", "Account", "CreateBy", "Salt", "Pwd", "Email", "Remark" });
            //关联角色表
            await _sysUserRoleService.Insert(new { sysUser.RoleId, UserId = res }, new string[] { "UserId", "RoleId" });

            return OpReturn(res, "添加");
        }
        /// <summary>
        /// 修改保存
        /// </summary>
        /// <param name="sysUser"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<InfoModel> EditSave([FromBody]RequestUser sysUser)
        {
            #region 数据封装
            sysUser.UpdateTime = DateTime.Now;
            sysUser.UpdateBy = HttpContext.User.Claims.Where(o => o.Type == ClaimTypes.NameIdentifier).FirstOrDefault().Value;
            #endregion

            int res = await _sysUserService.Edit(sysUser, new string[] { "Name", "Phone", "Status", "Sex", "UpdateBy", "UpdateTime", "Email", "Remark" });

            #region 关联角色表
            await _sysUserRoleService.Edit(sysUser.RoleId.ToString(), sysUser.Id.ToString());
            #endregion
            return OpReturn(res, "修改");
        }
        /// <summary>
        /// 批量删除用户
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<InfoModel> Delete([FromBody]RequestDelete ids)
        {
            int res = await _sysUserService.Delete(ids.ids);
            return OpReturn(res, "删除");
        }

        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <param name="param">条件</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<InfoModel> Export([FromBody]RequestExcel param)
        {
            int res = 0;
            string msg = "下载失败";
            try
            {
                #region 查询条件
                string sqlWhere = "";
                if (param.account != "")
                {
                    sqlWhere = $" {sqlWhere} and Account like concat('%', @account, '%')";
                }
                if (param.phone != "")
                {
                    sqlWhere = $" {sqlWhere} and Phone  like concat('%', @phone, '%') ";
                }
                if (param.status != "")
                {
                    sqlWhere = $" {sqlWhere} and Status=@status ";
                }
                if (param.startTime != "")
                {
                    sqlWhere = $" {sqlWhere} and date_format(CreateTime,'%y%m%d') >= date_format(@startTime,'%y%m%d')";
                }
                if (param.endTime != "")
                {
                    sqlWhere = $" {sqlWhere} and date_format(CreateTime,'%y%m%d') <= date_format(@endTime,'%y%m%d')";
                }
                #endregion

                msg = await _sysUserService.Export(param, sqlWhere);
                res = 1;
            }
            catch (Exception ex)
            {

            }
            return OpReturn(res, "", msg);
        }
        /// <summary>
        /// 导入Excel
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<InfoModel> Import()
        {
            #region 保存到本地
            var formFile = Request.Form.Files[0];
            string Path = Appsettings.app(new string[] { "AppSettings", "File", "Upload", "Excel" });
            var filePath = Path + DateTime.Now.ToString("yyyMMDDHHmmssfff_") + formFile.FileName;

            if (formFile.Length > 0)
            {
                if (!Directory.Exists(Path))
                {
                    Directory.CreateDirectory(Path);
                }

                using (var stream = new FileStream(filePath, FileMode.Create))
                {
                    await formFile.CopyToAsync(stream);
                }
            }
            #endregion

            #region 导入数据库
            string op = HttpContext.User.Claims.Where(o => o.Type == ClaimTypes.NameIdentifier).FirstOrDefault().Value;
            int res = await _sysUserService.Import(filePath, op);
            #endregion
            return OpReturn(res, "导入");
        }
        #endregion
    }
}